package com.ship.boats.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.ship.boats.domain.dto.QueryTimeZoneSwitchingRq;
import com.ship.boats.domain.vo.QueryTimeZoneSwitchingInfo;
import com.ship.boats.mapper.BoatsExportMapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.base.Export;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.mapping.Label;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <b>ExportDownloadUtil</b>
 *
 * @description: ExportDownloadUtil <br>
 * @date: 2024/3/22 11:33 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Configuration
public class ExportDownloadUtil extends BaseServiceImpl<BoatsExportMapper,Export> {
    @Value("${file_server.host}")
    private String fileServerHost;

    @Autowired
    private RemoteFileService remoteFileService;

    public String pageExport(List<?> exportList, Field[] fields, List<String> table, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();
            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }

            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                field.setAccessible(true);
                headerRow.createCell(i).setCellValue(getFieldLabel(field));
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            System.out.println("数据导出文件上传结果日志打印："+result);
            File excelFile = new File(excelName);
            if (excelFile.exists()) {
                excelFile.delete();
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getFieldLabel(Field field) {
        Label labelAnnotation = field.getAnnotation(Label.class);
        if (labelAnnotation != null) {
            String[] labelValues = labelAnnotation.value();
            if (labelValues.length > 0) {
                return labelValues[0]; // 返回数组的第一个元素作为Label值
            }
        }
        return field.getName(); // 如果注解不存在或者数组为空，返回字段名作为默认值
    }

    public List<String> listStrByModuleAndUser(String spInspectionsCertificates, Long currentUserId) {
        return baseMapper.listStrByModuleAndUser(spInspectionsCertificates,currentUserId);
    }

    public String  exportUtil(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();

            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }
            if (CollectionUtil.isNotEmpty(tableNameList)){
                for (int i = 0; i < tableNameList.size(); i++) {
                    headerRow.createCell(i).setCellValue(tableNameList.get(i));
                }
            }else {
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    headerRow.createCell(i).setCellValue(getFieldLabel(field));
                }
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            System.out.println("数据导出文件上传结果日志打印："+result);
            if (file.exists()) {
                if (file.delete()) {
                }
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();
//            String oldPart = "http://10.75.33.149:9300/statics";
//            String newPart = "https://lngshipping.cgp.cnooc/api/file/statics";
//
//            if (url.contains("http://10.75.33.149")) {
//                String newUrl = url.replace(oldPart, newPart);
//                return newUrl;
//            } else {
//                return url;
//            }

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public String  exportUtilDate(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();

            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }
            if (CollectionUtil.isNotEmpty(tableNameList)){
                for (int i = 0; i < tableNameList.size(); i++) {
                    headerRow.createCell(i).setCellValue(tableNameList.get(i));
                }
            }else {
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    headerRow.createCell(i).setCellValue(getFieldLabel(field));
                }
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            System.out.println("数据导出文件上传结果日志打印："+result);
            if (file.exists()) {
                if (file.delete()) {
                }
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();
//            String oldPart = "http://10.75.33.149:9300/statics";
//            String newPart = "https://lngshipping.cgp.cnooc/api/file/statics";
//
//            if (url.contains("http://10.75.33.149")) {
//                String newUrl = url.replace(oldPart, newPart);
//                return newUrl;
//            } else {
//                return url;
//            }

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }

            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}
